<?php
  require_once('./db.php');
  require_once('./header.php');
  pr($_FILES);
  $flag = false;
  $msg = '';

  if(isset($_FILES['csvfile']['error']) && $_FILES['csvfile']['error']==0 ) {
    if($_FILES['csvfile']['type']=='application/vnd.ms-excel' ) {

      $src = $_FILES['csvfile']['tmp_name'];

      $dest = './tmp/'.uniqid().'.csv';

      if(is_uploaded_file($src)) {
        if(move_uploaded_file($src, $dest)) {
          echo "Copied...";

          $totalUsers = importCsvInDb('users',$dest);
          $msg = "$totalUsers users imported successfully";
        } else {
          $msg =  "Error while uploading..";
        }
      }
    } else {
      $msg = "Please upload CSV file";
    }
  }

  function importCsvInDb($tableName='',$csvPath='')
  {
    if($tableName=='' || $csvPath=='') return false;

      $columnArr = Array
        ('uname', 'email', 'password', 'added_date', 'modified_date', 'status', 'avatar');

    $fp = fopen($csvPath, 'r+');
    $count = 0;
    while($users = fgetcsv($fp)) {


      array_shift($users);

      if($count > 0 ) {
        $users = array_combine($columnArr,$users );
        pr($users);
        dbInsert($tableName,$users);
      }
      $count++;
    }
    return $count - 1;
  }

echo "<h4>$msg</h4>";
?>
<form action="" enctype="multipart/form-data" method="post">
  <input type="file" name="csvfile" required />
  <input type="submit" value="Import" />
</form>

<?php
  require_once('./footer.php');
